package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class IMService {
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0")
    private UsersApi usersApi;
    @Autowired
    private AnnouncementService announcementService;

    /**
     * 根据环信⽤户名查询⽤户信息
     *
     * @param userName 环信⽤户id
     * @return 用户对象
     */
    public UserInfoVo queryUserInfoByUserName(String userName) {

        // 查询环信账户
        HuanXinUser huanXinUser = this.huanXinApi.queryUserByUserName(userName);
        if (ObjectUtil.isEmpty(huanXinUser)) {
            // 没有查询到环信账户信息
            return null;
        }

        // 查询用户信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(huanXinUser.getUserId());
        if (ObjectUtil.isEmpty(userInfo)) {
            // 没有查询到用户信息
            return null;
        }

        // 封装数据
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);

        return userInfoVo;


    }

    /**
     * 添加好友
     *
     * @param friendId 好友id
     * @return 成功与否
     */
    public boolean contactUser(Long friendId) {
        // 通过本地线程，获取当前用户数据
        User user = UserThreadLocal.get();

        // 添加好友关系到本地数据库
        String usersId = this.usersApi.saveUsers(user.getId(), friendId);
        if (StrUtil.isNotEmpty(usersId)) {

            // 注册好友关系到环信
            return this.huanXinApi.addUserFriend(user.getId(), friendId);
        }
        return false;
    }

    /**
     * 查询联系⼈列表
     *
     * @param page     当前页
     * @param pageSize 页大小
     * @param keyword  关键字
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        // 通过本地线程，获取当前用户数据
        User user = UserThreadLocal.get();

        List<Users> usersList = null;
        // 先判断有无查询条件
        if (StrUtil.isNotEmpty(keyword)) {
            // 关键不为空，查询所有的好友，在后⾯进⾏关键字过滤
            usersList = this.usersApi.queryAllUsersList(user.getId());

        } else {
            // 关键字为空，进⾏分⻚查询
            usersList = this.usersApi.queryUsersList(user.getId(), page, pageSize).getRecords();
        }

        if (CollUtil.isEmpty(usersList)) {
            return pageResult;
        }

        // 获取所有的好友id
        List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");

        // 查询好友基本信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", friendIdList);
        if (StrUtil.isNotEmpty(keyword)) {
            queryWrapper.like("nick_name", keyword);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByQueryWrapper(queryWrapper);

        List<UsersVo> contactsList = new ArrayList<>();
        UsersVo usersVo = null;
        // 填充用户信息
        for (UserInfo userInfo : userInfoList) {
            usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId()); // 用户id
            usersVo.setAvatar(userInfo.getLogo()); // 头像
            usersVo.setNickname(userInfo.getNickName()); // 昵称
            usersVo.setGender(userInfo.getSex().name().toLowerCase()); // 性别
            usersVo.setAge(userInfo.getAge()); // 年龄
            usersVo.setCity(StringUtils.substringBefore(userInfo.getCity(), "-")); // 城市

            // 环信⽤户账号
            usersVo.setUserId("HX_" + String.valueOf(userInfo.getUserId())); // 环信id

            contactsList.add(usersVo);
        }


        // 封装数据并返回
        pageResult.setItems(contactsList);
        return pageResult;
    }


    /**
     * 查询消息点赞\喜欢\评论列表
     *
     * @param comments 点赞likes\喜欢loves\评论comments
     * @param page     当前页
     * @param pageSize 页大小
     * @return
     */
    public PageResult queryLikeOrLoveOrCommentListByUser(String comments, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        // 判断消息类型
        CommentType commentType = null;
        switch (comments) {
            case "likes":
                commentType = CommentType.LIKE;
                break;
            case "loves":
                commentType = CommentType.LOVE;
                break;
            case "comments":
                commentType = CommentType.COMMENT;
                break;
            default:
                break;
        }

        // 获取当前用户信息
        User user = UserThreadLocal.get();

        // 获取我的评论消息列表
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLikeOrLoveOrCommentListByUser(user.getId(), commentType, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        // 通过评论消息列表获取其对应用户的基本信息
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);
        Map<Long, UserInfo> userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getUserId, UserInfo -> UserInfo));

        List<MessageCommentVo> messageCommentVoList = new ArrayList<>();
        MessageCommentVo messageCommentVo = null;
        for (Comment record : records) {
            messageCommentVo = new MessageCommentVo();
            messageCommentVo.setId(record.getId().toHexString()); // 评论主键id

            UserInfo userInfo = userInfoMap.get(record.getUserId());
            messageCommentVo.setAvatar(userInfo.getLogo()); // 头像
            messageCommentVo.setNickname(userInfo.getNickName()); // 昵称
            messageCommentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "yyyy-MM-dd HH:mm"));

            messageCommentVoList.add(messageCommentVo);
        }

        pageResult.setItems(messageCommentVoList);
        return pageResult;
    }

    /**
     * 查询公告列表
     *
     * @param page     当前页
     * @param pageSize 页大小
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        IPage<Announcement> iPage = this.announcementService.queryList(page, pageSize);
        List<Announcement> records = iPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            // 没有查询到公告信息
            return pageResult;
        }

        List<AnnouncementVo> announcementVoList = new ArrayList<>();
        AnnouncementVo announcementVo = null;
        for (Announcement record : records) {
            announcementVo = new AnnouncementVo();
            announcementVo.setId(String.valueOf(record.getId())); // 主键id
            announcementVo.setTitle(record.getTitle()); // 标题
            announcementVo.setDescription(record.getDescription()); // 描述
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm")); // 创建时间

            announcementVoList.add(announcementVo);
        }


        // 封装并返回
        pageResult.setItems(announcementVoList);
        return pageResult;
    }

    /**
     * 解除好友关系
     *
     * @param friendId 用户id
     */
    public Boolean removeUser(Long friendId) {
        // 删除好有关系
        User user = UserThreadLocal.get();
        Boolean result = this.usersApi.removeUsers(user.getId(), friendId);
        if(result){
            // 将环信的好友关系注销
            return this.huanXinApi.removeUserFriend(user.getId(), friendId);
        }
        return false;
    }
}
